package com.sohh.demo;

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @description: 文件压缩 使用 NIO的 Channel
 * @author: ruoan
 * @date: 2021/2/21 15:57
 */
public class Test7 {

    public static void main(String[] args) {
        String path = "d:\\CC.zip";
        String JPG_PATH = "D:\\line99999.png";
        String FILE_NAME = JPG_PATH.split("\\\\")[1];
        
        File zipFile  = new File(path);
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
             WritableByteChannel writableByteChannel = Channels.newChannel(zipOutputStream)){
            long beginTime = System.currentTimeMillis();
            for (int i = 0; i < 1; i++) {
                try (FileChannel fileChannel = new FileInputStream(JPG_PATH).getChannel()){
                    zipOutputStream.putNextEntry(new ZipEntry(FILE_NAME));
                    //int temp = 0;
                    //while ((temp=bufferedInputStream.read())!=-1) {
                    //    bufferedOutputStream.write(temp);
                    //}
                    long FILE_SIZE = fileChannel.size(); //
                    System.out.println("FILE_SIZE=?"+FILE_SIZE);
                    fileChannel.transferTo(0, FILE_SIZE, writableByteChannel); // im

                }
            }
            long endTime = System.currentTimeMillis();
            System.out.println("花费时间："+(endTime-beginTime)+"ms");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }



}
